package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.Teacher;
import com.EAsystem.entity.User;
import com.EAsystem.entity.College;
import com.EAsystem.entity.Major;
import com.EAsystem.service.TeacherService;
import com.EAsystem.service.UserService;
import com.EAsystem.service.CollegeService;
import com.EAsystem.service.MajorService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class TeacherManagementController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private UserService userService;

    @Autowired
    private CollegeService collegeService;
    
    @Autowired
    private MajorService majorService;

    /**
     * 教师信息管理页面
     */
    @GetMapping("/teacher")
    public String teacherPage(@RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "5") int size,
                             @RequestParam(required = false) String teacherSearch,
                             Model model) {
        
        PageInfo<Teacher> pageInfo;
        
        // 根据条件查询
        if (teacherSearch != null && !teacherSearch.trim().isEmpty()) {
            Teacher searchTeacher = new Teacher();
            User user = new User();
            user.setRealName(teacherSearch.trim());
            searchTeacher.setUser(user);
            pageInfo = teacherService.findByCondition(searchTeacher, page, size);
        } else {
            pageInfo = teacherService.findAllByPage(page, size);
        }
        

        List<Integer> pageNumbers = new ArrayList<>();
        for (int i = 1; i <= pageInfo.getPages(); i++) {
            pageNumbers.add(i);
        }
        
        // 获取所有专业信息，用于新增/编辑模态框的下拉选择
        List<Major> majorList = majorService.findAll();
        
        model.addAttribute("teachers", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchTeacherName", teacherSearch);
        model.addAttribute("pageNumbers", pageNumbers);
        model.addAttribute("majorList", majorList);
        
        return "admin/teacher";
    }

    /**
     * 查看教师详情
     */
    @GetMapping("/teacher/view/{id}")
    @ResponseBody
    public Map<String, Object> viewTeacher(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Teacher teacher = teacherService.findById(id);
            if (teacher != null) {
                result.put("success", true);
                result.put("teacher", teacher);
            } else {
                result.put("success", false);
                result.put("message", "教师记录不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取教师信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除教师记录
     */
    @GetMapping("/teacher/delete/{id}")
    public String deleteTeacher(@PathVariable Integer id) {
        teacherService.delete(id);
        return "redirect:/admin/teacher";
    }

    /**
     * 批量删除教师记录
     */
    @GetMapping("/teacher/batchDelete")
    public String batchDeleteTeachers(@RequestParam("ids") String ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    teacherService.delete(Integer.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/admin/teacher";
    }

    /**
     * 获取学院列表
     */
    @GetMapping("/teacher/colleges")
    @ResponseBody
    public Map<String, Object> getColleges() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<College> colleges = collegeService.findAll();
            result.put("success", true);
            result.put("colleges", colleges);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取学院列表失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 新增教师
     */
    @PostMapping("/teacher/add")
    @ResponseBody
    public Map<String, Object> addTeacher(@RequestParam String username,
                                         @RequestParam String password,
                                         @RequestParam String realName,
                                         @RequestParam String teacherNo,
                                         @RequestParam(required = false) String phone,
                                         @RequestParam(required = false) String email,
                                         @RequestParam(required = false) Integer collegeId,
                                         @RequestParam(required = false) String title,
                                         @RequestParam(required = false) Integer gender) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查用户名是否已存在
            if (userService.findByUsername(username) != null) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                return result;
            }
            
            // 检查工号是否已存在
            if (teacherService.findByTeacherNo(teacherNo) != null) {
                result.put("success", false);
                result.put("message", "工号已存在");
                return result;
            }
            
            // 创建用户账号
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setRealName(realName);
            user.setRole(2); // 教师角色
            user.setStatus(1); // 正常状态
            
            boolean userSuccess = userService.add(user);
            if (!userSuccess) {
                result.put("success", false);
                result.put("message", "创建用户账号失败");
                return result;
            }
            
            // 获取刚创建的用户ID
            User createdUser = userService.findByUsername(username);
            
            // 创建教师记录
            Teacher teacher = new Teacher();
            teacher.setUser(createdUser);
            teacher.setTeacherNo(teacherNo);
            teacher.setPhone(phone);
            teacher.setEmail(email);
            teacher.setTitle(title);
            teacher.setGender(gender);
            
            // 设置学院信息
            if (collegeId != null && collegeId > 0) {
                List<College> colleges = collegeService.findAll();
                College selectedCollege = null;
                for (College college : colleges) {
                    if (college.getId().equals(collegeId)) {
                        selectedCollege = college;
                        break;
                    }
                }
                if (selectedCollege != null) {
                    teacher.setCollege(selectedCollege);
                }
            }
            
            boolean teacherSuccess = teacherService.add(teacher);
            if (teacherSuccess) {
                result.put("success", true);
                result.put("message", "新增教师成功");
            } else {
                userService.delete(createdUser.getId());
                result.put("success", false);
                result.put("message", "新增教师失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "新增教师失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 编辑教师
     */
    @PostMapping("/teacher/edit")
    @ResponseBody
    public Map<String, Object> editTeacher(@RequestParam Integer id,
                                          @RequestParam Integer userId,
                                          @RequestParam String username,
                                          @RequestParam(required = false) String password,
                                          @RequestParam String realName,
                                          @RequestParam String teacherNo,
                                          @RequestParam(required = false) String phone,
                                          @RequestParam(required = false) String email,
                                          @RequestParam(required = false) Integer collegeId,
                                          @RequestParam(required = false) String title,
                                          @RequestParam(required = false) Integer gender) {
        Map<String, Object> result = new HashMap<>();
        try {
            Teacher teacher = teacherService.findById(id);
            if (teacher == null) {
                result.put("success", false);
                result.put("message", "教师记录不存在");
                return result;
            }
            
            User user = userService.findById(userId);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户记录不存在");
                return result;
            }
            
            // 检查用户名是否被其他用户使用
            User existingUser = userService.findByUsername(username);
            if (existingUser != null && !existingUser.getId().equals(userId)) {
                result.put("success", false);
                result.put("message", "用户名已被其他用户使用");
                return result;
            }
            
            // 检查工号是否被其他教师使用
            Teacher existingTeacher = teacherService.findByTeacherNo(teacherNo);
            if (existingTeacher != null && !existingTeacher.getId().equals(id)) {
                result.put("success", false);
                result.put("message", "工号已被其他教师使用");
                return result;
            }
            
            // 更新用户信息
            user.setUsername(username);
            if (password != null && !password.trim().isEmpty()) {
                user.setPassword(password);
            }
            user.setRealName(realName);
            
            boolean userSuccess = userService.update(user);
            if (!userSuccess) {
                result.put("success", false);
                result.put("message", "更新用户信息失败");
                return result;
            }
            
            // 更新教师信息
            teacher.setTeacherNo(teacherNo);
            teacher.setPhone(phone);
            teacher.setEmail(email);
            teacher.setTitle(title);
            teacher.setGender(gender);
            
            // 更新学院信息
            if (collegeId != null && collegeId > 0) {
                List<College> colleges = collegeService.findAll();
                College selectedCollege = null;
                for (College college : colleges) {
                    if (college.getId().equals(collegeId)) {
                        selectedCollege = college;
                        break;
                    }
                }
                if (selectedCollege != null) {
                    teacher.setCollege(selectedCollege);
                }
            } else {
                teacher.setCollege(null);
            }
            
            boolean teacherSuccess = teacherService.update(teacher);
            if (teacherSuccess) {
                result.put("success", true);
                result.put("message", "编辑教师成功");
            } else {
                result.put("success", false);
                result.put("message", "编辑教师失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "编辑教师失败：" + e.getMessage());
        }
        return result;
    }
} 